package com.hctforgreen.greenservice.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Date;
import java.text.SimpleDateFormat;

import org.w3c.dom.Text;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.DebugActivity;
import com.hctforgreen.greenservice.LoginActivity;
import com.hctforgreen.greenservice.MainActivityV2;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.TechnicalDataActivityV4;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.model.PersonPotinsEntity;
import com.hctforgreen.greenservice.model.RelevanceEntity;

/**
 * 工具类
 * 
 * @author ld 20130403
 * 
 */
public class Utils {
	/**
	 * 计算图片的缩放值
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	private static Bitmap loadBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		options.inSampleSize = calculateInSampleSize(options, 1280, 427);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 设置edittext光标移到最后一个位置
	 * 
	 * @param e
	 */
	public static void setLastSelection(EditText e) {
		Editable editable = e.getText();
		e.requestFocus();
		e.setSelection(editable.length());
	}

	public static void showToastCenter(Activity act, String msg) {
		Toast tr = Toast.makeText(act, msg, Toast.LENGTH_SHORT);
		// tr.setGravity(Gravity.CENTER, 0, 0);
		tr.show();
	}

	public static void showToastTop(Activity act, String msg) {
		Toast tr = Toast.makeText(act, msg, Toast.LENGTH_SHORT);
		tr.setGravity(Gravity.TOP, 0, 0);
		tr.show();
	}

	public static void notice(Activity act, String title, String msg,
			OnClickListener click, OnClickListener cancel) {
		new AlertDialog.Builder(act).setMessage(msg)
				.setPositiveButton(R.string.dlg_ok, click)
				.setNegativeButton(R.string.dlg_cancel, cancel).show();
	}
	/**
	 * 
	 * @param act
	 * @param title
	 * @param msg
	 * @param buttonName_1 按钮名
	 * @param buttonName_2
	 * @param click_1 点击方法
	 * @param click_2
	 * 
	 * @author wuhs
	 */
	public static void notice(Activity act, String title, String msg, int buttonName_1, int buttonName_2,
			OnClickListener click_1, OnClickListener click_2) {
		Builder dialog = new AlertDialog.Builder(act).setMessage(msg)
				.setPositiveButton(buttonName_1, click_1)
				.setNegativeButton(buttonName_2, click_2);
		if(!title.equals("")||title!=null){
			dialog.setTitle(title);
		}
		dialog.show();
		
	}
	/**
	 * 开机密码简要对话框（显示条码和开机密码）
	 * 
	 * @param act
	 * @param title
	 * @param msg
	 * @param click
	 */
	public static void notice(Activity act, String title, String msg,
			OnClickListener click) {
		new AlertDialog.Builder(act).setMessage(msg)
				.setNeutralButton(R.string.dlg_ok, click).show();
	}

	/*
	 * 显示开机密码提醒信息
	 */
	public static void noticeTips(Activity act, String msg) {
		new AlertDialog.Builder(act).setTitle("温馨提示:").setMessage(msg)
				.setNeutralButton(R.string.dlg_ok, null).show();
	}

	/**
	 * 开机密码简要对话框显示提醒内容及跳转至资料按钮
	 * 
	 * @param act
	 * @param title
	 * @param msg
	 */
	public static void noticeAndSelect(final Activity act, final String msg,
			final String bookId) {

		AlertDialog.Builder builder = new Builder(act);
		builder.setTitle("温馨提示:")
				.setMessage(msg)
				.setPositiveButton("查看资料",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								DbController controller = new DbController(act);
								BookEntity entity = controller
										.getBookEntity(bookId);
								if (entity == null
										|| TextUtils.isEmpty(entity.id)) {
									Toast.makeText(act, "抱歉，找不到该资料，请先去刷新资料！",
											Toast.LENGTH_LONG).show();
									return;
								}
								EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
								try {
									catalogUtil.startEntryCatalogActivity(act,
											entity, true);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).setNeutralButton(R.string.dlg_cancel, null).create()
				.show();
	}

	private static void startTechDataActivity(Activity mActivity,
			MachineEntity mMachineEntity, SerieEntity serieEntity,
			ChildSerieEntity childSerieEntity) {
		Intent intent = new Intent();
		intent.setClass(mActivity, TechnicalDataActivityV4.class);
		intent.putExtra(HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY,
				mMachineEntity);
		intent.putExtra(HctConstants.ON_ACTIVITY_KEY_SERIES_ENTITY, serieEntity);
		intent.putExtra(HctConstants.ON_ACTIVITY_KEY_CHILD_SERIE_ENTITY,
				childSerieEntity);
		mActivity.startActivity(intent);
	}

	private static ChildSerieEntity initChildSerieEntity(
			MachineEntity machineEntity, SerieEntity serieEntity) {
		ChildSerieEntity childSerieEntity = null;
		if (serieEntity == null || serieEntity.childList == null) {
			return null;
		}
		for (ChildSerieEntity cEntity : serieEntity.childList) {
			if (machineEntity.childSeriesId.equals(cEntity.childSeriesId)) {
				childSerieEntity = cEntity;
			}
		}
		return childSerieEntity;
	}

	/**
	 * 获取当前时间（格式:2013-06-18 17:36:00）
	 * 
	 * @return
	 */
	public static String getNowTime() {
		Date now = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = dateFormat.format(now);
		return str;
	}

	/**
	 * 获取当前日期（格式:2013-06-18）
	 * 
	 * @return
	 */
	public static String getNowDate() {
		Date now = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String str = dateFormat.format(now);
		return str;
	}

	/**
	 * 获取当前时间（格式:HH:mm）
	 * 
	 * @return
	 */
	public static String getNowTimeHM() {
		Date now = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
		String str = dateFormat.format(now);
		return str;
	}
	

	/**
	 * 创建临时目录
	 * 
	 * @return
	 */
	public static String getTempDir(Application app) {
		String tempPath = getDir(app) + "/Android/data/" + app.getPackageName()
				+ "/temp/";
		mkdir(tempPath);
		return tempPath;
	}

	/**
	 * 获取根目录
	 * 
	 * @return
	 */
	public static String getDir(Application app) {
		String sdcard = getSDRoot();
		if (sdcard != null)
			return sdcard;

		return getInternalDirectory(app);
	}

	/**
	 * 创建目录
	 * 
	 * @param path
	 */
	public static void mkdir(String path) {
		File f = new File(path);

		if (f.isFile()) {
			f.delete();
		}

		if (!f.exists()) {
			f.mkdirs();
		}
	}

	/**
	 * 获取手机本身存储
	 * 
	 * @return
	 */
	public static String getInternalDirectory(Application app) {
		return app.getFilesDir().getAbsolutePath();
	}

	/**
	 * 获取手机sd卡存储
	 * 
	 * @return
	 */
	public static String getSDRoot() {

		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	/**
	 * 判断字符串里是否有中文
	 * 
	 * @param s
	 * @return
	 */
	public static boolean chineseValid(String s) {

		int length = s.length();

		byte[] b;

		for (int i = 0; i < length; i++)

		{

			b = s.substring(i).getBytes();

			if ((b[0] & 0xff) > 128)

				return true;

		}

		return false;

	}

	/**
	 * 判断网络是否连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 判断wifi网络是否连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWifiNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mNetworkInfo != null) {
				return mNetworkInfo.isConnected();
			}
		}
		return false;
	}

	/**
	 * gps是否打开
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isGpsValid(Context context) {
		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	/**
	 * 获取sd卡路径 双sd卡时，获得的是外置sd卡
	 * 
	 * @return
	 */
	public static String getSDCardPath() {
		String cmd = "cat /proc/mounts";
		Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
		BufferedInputStream in = null;
		BufferedReader inBr = null;
		try {
			Process p = run.exec(cmd);// 启动另一个进程来执行命令
			in = new BufferedInputStream(p.getInputStream());
			inBr = new BufferedReader(new InputStreamReader(in));

			String lineStr;
			while ((lineStr = inBr.readLine()) != null) {
				// 获得命令执行后在控制台的输出信息
				Log.i("CommonUtil:getSDCardPath", lineStr);
				if (lineStr.contains("sdcard")
						&& lineStr.contains(".android_secure")) {
					String[] strArray = lineStr.split(" ");
					if (strArray != null && strArray.length >= 5) {
						String result = strArray[1].replace("/.android_secure",
								"");
						return result;
					}
				}
				// 检查命令是否执行失败。
				if (p.waitFor() != 0 && p.exitValue() == 1) {
					// p.exitValue()==0表示正常结束，1：非正常结束
					Log.e("CommonUtil:getSDCardPath", "命令执行失败!");
				}
			}
		} catch (Exception e) {
			Log.e("CommonUtil:getSDCardPath", e.toString());
			// return Environment.getExternalStorageDirectory().getPath();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if (inBr != null) {
					inBr.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return Environment.getExternalStorageDirectory().getPath();
	}

	// 查看所有的sd路径
	public static String[] getSDCardPathEx(Context activity) {

		String[] mount = null;
		String exSd = getExternalPath();
		if (!sdCard.equals(exSd)
				&& exSd != null
				&& exSd.trim().length() > 0
				&& Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
			mount = new String[2];
			mount[0] = sdCard;
			if (android.os.Build.VERSION.SDK_INT >= 19) {// 4.4系统或以上
				activity.getExternalFilesDir(null).getAbsolutePath();// 这句代码执行后才会创建扩展目录
				mount[1] = exSd + "/Android/data/" + packageName + "/files";
				// System.out.println(mount[0] + "----:" + mount[1]);
				// mount[1] =
			} else {
				mount[1] = exSd;
				// System.out.println(mount[0] + "------:" + mount[1]);
			}
		} else {
			mount = new String[1];
			mount[0] = sdCard;
			// System.out.println(mount[0]);
		}

		return mount;
	}

	private static String packageName = "com.hctforgreen.greenservice";// "com.hctforgreen.greenservice";
	private static String cmd = "cat /proc/mounts";
	private static String format = "sdcard";
	private static String sdCard = Environment.getExternalStorageDirectory()
			.getAbsolutePath();

	/**
	 * 獲取外置SDCard的絕對路徑
	 * 
	 * @return
	 */
	public static String getExternalPath() {
		BufferedReader read = null;
		String external_SDCard = "";
		Runtime runtime = Runtime.getRuntime();
		try {
			Process process = runtime.exec(cmd);
			read = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			String line;
			while ((line = read.readLine()) != null) {
				// if (line.toLowerCase().contains(format)
				// && line.contains(".android-secure")) {
				if (line.toLowerCase().contains(format)) {
					String[] array = line.split(" ");
					if (array != null && array.length >= 5) {
						String temp = array[1].replace("/.android_secure", "");
						if (sdCard.equals(temp)
								&& (android.os.Build.VERSION.SDK_INT >= 19 || android.os.Build.MANUFACTURER
										.toLowerCase().contains("samsung"))) {
							return external_SDCard;
						} else {
							external_SDCard = temp;
							if (!external_SDCard.contains("storage")) {
								external_SDCard = "";
							}
						}
					}
				}
			}
		} catch (Exception e) {
			external_SDCard = sdCard;
			e.printStackTrace();
		} finally {
			// IOUtils.freeResource(read, null);
			try {
				read.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return external_SDCard;
	}

	/**
	 * 
	 * @param activity
	 * @param points
	 *            积分
	 * @param operName
	 *            操作
	 * @param showToast是否显示加分弹框
	 */
	public static void submitPoints(final Activity activity, final int points,
			final String operName, final boolean showToast) {
		final String personId = LoginResultStoreUtil.get(activity).personId;
		new Thread() {
			public void run() {
				HctController controller = new HctController(activity);
				try {
					HctResult hctResult = controller.submitPoint(activity,
							personId, points + "");
					if (hctResult.status == HctConstants.STATUS_SUCCESS) {
						final PersonPotinsEntity entity = (PersonPotinsEntity) hctResult.data;

						if (entity != null) {
							activity.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									if (entity.addPoints != null
											&& entity.addPoints.trim().length() > 0) {
										Integer addPoint = Integer
												.parseInt(entity.addPoints);
										if (addPoint > 0) {
											PersonPointsStoreUtil.save(
													activity, entity);
											Intent intent = new Intent(
													MainActivityV2.UPADTE_PERSON_POINTS_ACTION_NAME);
											activity.sendBroadcast(intent);

											if (showToast) {
												showAddPointsToast(activity,
														points, operName);
											}
										}
									}
								}
							});
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	/**
	 * 显示加积分成功弹框
	 * 
	 * @param activity
	 * @param points
	 * @param operName
	 */
	public static void showAddPointsToast(Activity activity, int points,
			String operName) {
		Toast toast = new Toast(activity);
		View view = LayoutInflater.from(activity).inflate(
				R.layout.add_points_toast, null);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		TextView operNameTv = (TextView) view.findViewById(R.id.oper_name);
		TextView pointsTv = (TextView) view.findViewById(R.id.tv_points);
		operNameTv.setText(operName);
		pointsTv.setText("+" + points);
		toast.setView(view);
		toast.show();
	}

	public static void showImgCount(RadioGroup viewGroup, int count,
			Activity activity) {
		RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(10,
				10);
		viewGroup.removeAllViews();
		for (int i = 0; i < count; i++) {
			RadioButton radioButton = new RadioButton(activity);
			radioButton.setButtonDrawable(R.drawable.gei);
			radioButton.setBackgroundResource(R.drawable.radio_selector);
			radioButton.setText("");
			radioButton.setGravity(Gravity.CENTER);
			layoutParams.setMargins(5, 2, 5, 2);
			radioButton.setLayoutParams(layoutParams);

			viewGroup.addView(radioButton);
			if (i == 0) {
				radioButton.setChecked(true);
			}
		}

	}

	public static int dipToPx(int dip, Context context) {
		final float scale = context.getResources().getDisplayMetrics().density;
		int px = (int) (dip * scale + 0.5f);
		return px;
	}

	public static int pxToDip(int px, Context context) {
		final float scale = context.getResources().getDisplayMetrics().density;
		int dip = (int) (px / scale + 0.5f);
		return dip;
	}
}
